package com.itheima03;

import java.util.Arrays;

/**
 * @author Xiao
 * @date 2021/7/20
 */
public class ArrayDemo03 {
    /**
     *  二分查找
     */
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11, 13, 15};
//        int num = 20;
//        int index = binaryGetIndex(arr, num);
        int index1 = Arrays.binarySearch(arr, 9);   //7
        int index2 = Arrays.binarySearch(arr, 16);   //-9
        int index3 = Arrays.binarySearch(arr, 0);   //-1
        System.out.println("index:" + index3);
    }

    private static int binaryGetIndex(int[] arr, int num) {
        int index = -1;
        int max = arr.length - 1;
        int min = 0;
        while (min <= max) {
//            int middle = (max + min)/2;
            int middle = (max + min) >> 1;      //位运算符：num >> 1 → num/2
            if (num == arr[middle]) {
                index = middle;
                break;
            } else if (num < arr[middle]) {
                max = middle - 1;
            } else {
                min = middle + 1;
            }
        }
        return index;
    }
}
